package pers.ljf.escloud.controller.app;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.HandlerMapping;
import pers.ljf.escloud.common.dto.FileItemDTO;
import pers.ljf.escloud.common.utils.HttpUtil;
import pers.ljf.escloud.common.utils.UserInfoUtils;
import pers.ljf.escloud.service.modules.app.FileService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
@RequestMapping("/app/file")
@Controller
public class DirectLinkController {

    @Resource
    private FileService fileService;

    /**
     * 必须处于登录状态才能访问此链接
     * 某个文件的aliyun oss直链, 然后重定向到文件真正的oss 直链地址.
     *
     * @return 重定向至文件直链
     */
    @GetMapping("/directLink/**")
    public String directlink(final HttpServletRequest request,
                             final HttpServletResponse response) throws IOException {
//        DriveConfig driveConfig = driveConfigService.findById(driveId);
//        Boolean enable = driveConfig.getEnable();
//        if (!enable) {
//            throw new NotEnabledDriveException();
//        }
//        String path1 = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString();
//        String path2 = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();
//        String args = new AntPathMatcher().extractPathWithinPattern(path2, path1);
//        String path = new String(p.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        String path = (String) request.getAttribute(
                HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        AntPathMatcher apm = new AntPathMatcher();
        //"财务/app.py"
        String filePath = apm.extractPathWithinPattern(bestMatchPattern, path);
        //不包含企业名，从登录信息获得
        String fullPath = UserInfoUtils.get().getBasePath() + '/' + filePath;
        FileItemDTO fileItem = fileService.getFileItem(fullPath);

        String url = fileItem.getUrl();

        if (StrUtil.equalsIgnoreCase(FileUtil.extName(fileItem.getName()), "m3u8")) {
            String textContent = HttpUtil.getTextContent(url);
            response.setContentType("application/vnd.apple.mpegurl;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(textContent);
            out.flush();
            out.close();
            return null;
        }
        return "redirect:" + url;
    }
}
